package com.anfeng.cms.service.impl;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Component;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 吴朋
 * @date 2019/7/16
 */
@Setter
@Slf4j
@Component
public class ExcelSupport {

    @SafeVarargs
    public final void export(HttpServletRequest httpServletRequest, HttpServletResponse response, String fileName, Content<?>... datas) {
        ServletOutputStream exportXls = null;
        try {
            //响应头
            fileName = fileName.substring(0, fileName.indexOf("."));
            fileName = fileName+".xls";
            String agent = httpServletRequest.getHeader("User-agent");
            if(agent.indexOf("Firefox") != -1) {
                response.addHeader("content-Disposition", "attachment;fileName==?UTF-8?B?"+new String(Base64.encodeBase64(fileName.getBytes("utf-8")))+"?=");
            } else {
                response.addHeader("content-Disposition", "attachment;fileName="+URLEncoder.encode(fileName, "utf-8"));
            }
            response.setContentType("application/vnd.ms-excel");
            exportXls = response.getOutputStream();

            List<Map<String, Object>> list = new ArrayList<>();
            for (Content<?> data : datas) {
                Map<String, Object> map = new HashMap<>(16);
                map.put("title", new ExportParams(null, data.sheetName));
                map.put("entity", data.type);
                map.put("data", data.rows);
                list.add(map);
            }
            Workbook workbook = ExcelExportUtil.exportExcel(list, ExcelType.HSSF);
            workbook.write(exportXls);
            workbook.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (exportXls != null) {
                try {
                    exportXls.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static class Content<T> {
        String sheetName;
        List<T> rows;
        Class<T> type;

        public Content(String sheetName, List<T> rows, Class<T> type) {
            this.sheetName = sheetName;
            this.rows = rows;
            this.type = type;
        }
    }

    /**
     * 根据文件名下载模板文件
     * @param httpServletRequest 请求信息
     * @param response 响应信息
     * @param fileName 文件名称
     */
    public final void downLoadTemplete(HttpServletRequest httpServletRequest, HttpServletResponse response, String fileName) {
        FileInputStream input = null;
        ServletOutputStream exportXls = null;
        try {
            if (StringUtils.isBlank(fileName)) {
                return;
            }
            //设置要下载的文件的名称
            response.setHeader("Content-disposition", "attachment;fileName=" + fileName);
            //通知客服文件的MIME类型
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            //获取文件的路径
            String filePath = getClass().getResource("/templates/excel/" + fileName).getPath();
            input = new FileInputStream(filePath);
            exportXls = response.getOutputStream();
            byte[] b = new byte[2048];
            int len;
            while ((len = input.read(b)) != -1) {
                exportXls.write(b, 0, len);
            }
            //修正 Excel在“xxx.xlsx”中发现不可读取的内容。是否恢复此工作薄的内容？如果信任此工作簿的来源，请点击"是"
            response.setHeader("Content-Length", String.valueOf(input.getChannel().size()));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (exportXls != null) {
                try {
                    exportXls.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (input != null) {
                try {
                    input.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
